在前面的章節中,我們學習了 Maven 的繼承和聚合機制。但隨著專案規模的擴大,您可能會遇到一個棘手的問題:當您需要管理大量相關套件的版本時,單一繼承的限制就會顯現出來。今天我們來學習 Maven 的 BOM 機制,如何來解決這樣的問題?
Maven 的 POM 繼承就像 Java 類別一樣,只支援單一繼承:
實際遇到的問題
假設您的專案需要使用以下套件組合:
Spring Boot Dependencies
困難點:
BOM 的解決方案
BOM (Bill of Materials) 是一種特殊的 POM 文件,它的作用是:
<dependencyManagement>
設置我們參考我們day15的專案,並引入Spring Boot Dependencies
來統一我們的版本控管,詳細Spring Boot統一版本設置請點我
父層pom.xml設定,<dependency>
的type
要設為pom,dependency scope要設為import
<project>
<groupId>com.mycompany</groupId>
<artifactId>myApp</artifactId>
<version>1.0-SNAPSHOT</version>
<name>myApp</name>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<!-- 匯入 Spring Boot BOM -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.5.6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- 這些就不用再寫版本號了,因為 BOM 幫你統一管理 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<modules>
<module>core</module>
<module>service</module>
<module>infrastructure</module>
<module>web</module>
</modules>
</project>
今天我們學習了 Maven BOM (Bill of Materials) 機制,透過<scope>import</scope>
來統一管理大量相關套件版本